<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="字典类型名称/编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row class="table-container" :gutter="5">
      <el-col :span="14">
        <el-card shadow="never" style="height: 100%">
          <template #header>
            <el-button
              v-hasPerm="['sys:dict:add']"
              type="success"
              @click="openDialog(undefined, false)"
              ><i-ep-plus />新增分类</el-button
            >
            <el-button
              v-hasPerm="['sys:dict:del']"
              type="danger"
              :disabled="ids.length === 0"
              @click="handleDelete(undefined, false)"
              ><i-ep-delete />删除分类</el-button
            >
          </template>
          <el-table
            v-loading="loading"
            highlight-current-row
            :data="dictTypeList"
            border
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            class="fix-item"
            style="--fix-top-height: 242px"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="名称"
              prop="name"
              align="center"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="编码"
              prop="code"
              align="center"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="备注"
              prop="remark"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column label="排序" prop="sort" />
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="150"
            >
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:dict:add']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="openDialog(scope.row, false)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  v-hasPerm="['sys:dict:del']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleDelete(scope.row.id, false)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-model:total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card shadow="never" style="height: 100%">
          <template #header>
            <el-button
              v-hasPerm="['sys:dict:add']"
              type="success"
              @click="openDialog(undefined, true)"
              :disabled="!selectedDictType"
              ><i-ep-plus />新增子级</el-button
            >
            <el-button
              v-hasPerm="['sys:dict:del']"
              type="danger"
              :disabled="idsChildren.length === 0"
              @click="handleDelete(undefined, true)"
              ><i-ep-delete />删除子级</el-button
            >
          </template>
          <el-table
            v-loading="loadingRight"
            highlight-current-row
            :data="dictChildrenList"
            border
            @selection-change="handleSelectionChangeChildren"
            class="fix-item"
            style="--fix-top-height: 242px"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="名称"
              prop="name"
              align="center"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="编码"
              prop="code"
              align="center"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="备注"
              prop="remark"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column label="排序" prop="sort" />
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="150"
            >
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:dict:add']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="openDialog(scope.row, true)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  v-hasPerm="['sys:dict:del']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleDelete(scope.row.id, true)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-model:total="totalChildren"
            v-model:page="queryParamsChildren.pageNo"
            v-model:limit="queryParamsChildren.pageSize"
            @pagination="handleQueryChildren"
          />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="上级名称" v-if="parentName">
          <el-input v-model="parentName" disabled />
        </el-form-item>
        <el-form-item label="字典名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入字典名称"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入字典编码"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="200"
            placeholder="字典类型备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
            :max="999"
            step-strictly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<!--字典类型-->
<script setup lang="ts">
import { getDictPage, saveDict, deleteDict } from "@/api/dict";

import { DictPageVO, DictQuery, DictForm } from "@/api/dict/types";

defineOptions({
  name: "DictType",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const loadingRight = ref(false);
const ids = ref<string[]>([]);
const idsChildren = ref<string[]>([]);
const total = ref(0);
const totalChildren = ref(0);

// 分类查询参数
const queryParams = reactive<DictQuery>({
  pageNo: 1,
  pageSize: 10,
  pcode: "0",
});

// 选项查询参数
const queryParamsChildren = reactive<DictQuery>({
  pageNo: 1,
  pageSize: 10,
  pcode: "0",
});

// 分类列表
const dictTypeList = ref<DictPageVO[]>();
// 选项列表
const dictChildrenList = ref<DictPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

// 当前选中的字典类型
const selectedDictType = ref<DictPageVO>(null);

// 表单
const formData = reactive<DictForm>({
  sort: 0,
  pcode: "0",
});
const parentName = ref<string>("");

const rules = reactive({
  name: [{ required: true, message: "请输入字典类型名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入字典类型编码", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getDictPage(queryParams)
    .then(({ data }) => {
      dictTypeList.value = data.content;
      total.value = data.totalElements;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询 */
function handleQueryChildren() {
  loadingRight.value = true;
  const row = selectedDictType.value;
  Object.assign(queryParamsChildren, { pcode: row.code });
  getDictPage(queryParamsChildren)
    .then(({ data }) => {
      dictChildrenList.value = data.content;
      totalChildren.value = data.totalElements;
    })
    .finally(() => {
      loadingRight.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNo = 1;
  // checkbox 选择值清空
  ids.value = [];
  // 选中清空
  selectedDictType.value = null;
  // 清空上级名称
  parentName.value = "";
  handleQuery();
}

/** 类型-行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 选项-行复选框选中  */
function handleSelectionChangeChildren(selection: any) {
  idsChildren.value = selection.map((item: any) => item.id);
}

/**
 * 字典大类点击事件
 */
function handleRowClick(row: DictPageVO) {
  selectedDictType.value = row;
  handleQueryChildren();
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(row: DictPageVO, isChildren?: boolean) {
  dialog.visible = true;

  if (row) {
    if (isChildren) {
      // 编辑右边列表
      dialog.title = "修改字典选项";
      parentName.value = selectedDictType.value.name;
    } else {
      // 编辑左边列表
      dialog.title = "修改字典类型";
      parentName.value = "";
    }
    Object.assign(formData, row);
  } else {
    if (isChildren) {
      // 新增右边列表
      const selectCode = selectedDictType.value.code;
      if (!selectCode) {
        ElMessage.error("请选择上级字典类型");
      }
      // 展示上级名称
      parentName.value = selectedDictType.value.name;
      // 设置上级编码
      formData.pcode = selectCode;
      dialog.title = "新增字典选项";
    } else {
      // 新增左边列表
      // 设置上级编码为0， 清空上级名称
      formData.pcode = "0";
      parentName.value = "";
      dialog.title = "新增字典类型";
    }
  }
}

/** 字典类型表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const dictTypeId = formData.id;
      saveDict(formData)
        .then(() => {
          if (dictTypeId) {
            ElMessage.success("修改成功");
          } else {
            ElMessage.success("新增成功");
          }
          closeDialog();
          // 如果是选项，左边列表不刷新
          if (formData.pcode == "0") {
            handleQuery();
          } else {
            handleQueryChildren();
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}

/** 关闭字典类型弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置字典类型表单 */
function resetForm() {
  dataFormRef.value.resetFields && dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate && dataFormRef.value.clearValidate();

  formData.id = undefined;
}

/** 删除字典类型 */
function handleDelete(id?: string, isChildren?: boolean) {
  const values = isChildren ? idsChildren.value : ids.value;
  const idList = id ? [id] : values;
  if (!idList && idList.length) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteDict(idList).then(() => {
      ElMessage.success("删除成功");
      // 如果是选项，左边列表不刷新
      if (isChildren) {
        handleQueryChildren();
      } else {
        resetQuery();
      }
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
